<template>
  <div class="dashboard">
    <el-row :gutter="20" class="mb-20" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
      <el-col :span="12">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="fetchStats"
          style="width: 100%"
        />
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mb-20" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-title">公司总数</div>
          <div class="stat-value">{{ stats.companyCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-title">港口总数</div>
          <div class="stat-value">{{ stats.portCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-title">仓库总数</div>
          <div class="stat-value">{{ stats.warehouseCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-title">用户总数</div>
          <div class="stat-value">{{ stats.userCount }}</div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mb-20" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-title">区间入库总量</div>
          <div class="stat-value">{{ stats.totalIn }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-title">区间出库总量</div>
          <div class="stat-value">{{ stats.totalOut }}</div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-title">区间费用总额</div>
          <div class="stat-value">{{ stats.totalFee }} 元</div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
      <el-col :span="24">
        <el-card shadow="hover">
          <div class="stat-title">入库/出库趋势图</div>
          <div id="trend-chart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- CUSTOMER角色显示欢迎信息 -->
    <el-row v-if="userStore.userInfo?.role === 'CUSTOMER'">
      <el-col :span="24">
        <el-card shadow="hover">
          <div class="welcome-message">
            <h2>欢迎使用港口堆存费管理系统</h2>
            <p>您可以使用左侧菜单查看您的入库和出库记录</p>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { getAllCompanies } from '@/api/company'
import { getAllPorts } from '@/api/port'
import { getAllWarehouses } from '@/api/warehouse'
import { getAllUsers } from '@/api/user'
import { getStorageInList, getStorageOutList } from '@/api/storage'
import { calculateStorageFee } from '@/api/fee'
import { getStatisticsSummary } from '@/api/statistics'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const stats = ref({
  companyCount: 0,
  portCount: 0,
  warehouseCount: 0,
  userCount: 0,
  totalIn: 0,
  totalOut: 0,
  totalFee: 0
})

const trendData = ref({
  dates: [],
  inCounts: [],
  outCounts: []
})

const dateRange = ref([])

const fetchStats = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) return
  const [start, end] = dateRange.value
  const startDate = new Date(start)
  const endDate = new Date(end)
  const res = await getStatisticsSummary({
    start: start instanceof Date ? start.toISOString().slice(0, 10) : start,
    end: end instanceof Date ? end.toISOString().slice(0, 10) : end
  })
  stats.value.totalIn = res.data.totalIn
  stats.value.totalOut = res.data.totalOut
  stats.value.totalFee = res.data.totalFee

  // 公司、港口、仓库、用户数量
  const [companyRes, portRes, warehouseRes, userRes] = await Promise.all([
    getAllCompanies(),
    getAllPorts(),
    getAllWarehouses(),
    getAllUsers()
  ])
  stats.value.companyCount = companyRes.data.length
  stats.value.portCount = portRes.data.length
  stats.value.warehouseCount = warehouseRes.data.length
  stats.value.userCount = userRes.data.length

  // 获取所有入库/出库数据（可优化为后端接口支持区间查询）
  const [inRes, outRes] = await Promise.all([
    getStorageInList(),
    getStorageOutList()
  ])
  // 生成区间内所有日期
  const dates = []
  const inCounts = []
  const outCounts = []
  for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
    const dateStr = d.toISOString().slice(0, 10)
    dates.push(dateStr)
    inCounts.push(inRes.data.filter(item => item.inDate && item.inDate.startsWith(dateStr)).length)
    outCounts.push(outRes.data.filter(item => item.outDate && item.outDate.startsWith(dateStr)).length)
  }
  trendData.value = { dates, inCounts, outCounts }
  renderChart()
}

const renderChart = () => {
  const chartDom = document.getElementById('trend-chart')
  if (!chartDom) return
  const myChart = echarts.init(chartDom)
  myChart.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['入库', '出库'] },
    xAxis: { type: 'category', data: trendData.value.dates },
    yAxis: { type: 'value' },
    series: [
      { name: '入库', type: 'line', data: trendData.value.inCounts },
      { name: '出库', type: 'line', data: trendData.value.outCounts }
    ]
  })
}

onMounted(() => {
  // 只有非CUSTOMER角色才加载统计数据
  if (userStore.userInfo?.role !== 'CUSTOMER') {
    // 默认选中本月
    const now = new Date()
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
    const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
    dateRange.value = [firstDay, lastDay]
    fetchStats()
  }
})
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}
.stat-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
}
.stat-value {
  font-size: 28px;
  color: #409EFF;
  text-align: center;
  font-weight: bold;
}
.welcome-message {
  text-align: center;
  padding: 40px;
}
.welcome-message h2 {
  color: #409EFF;
  margin-bottom: 20px;
}
.welcome-message p {
  color: #666;
  font-size: 16px;
}
</style> 